package com.learn.security.oauth2.auth.server.service.security;

import cn.hutool.core.collection.CollUtil;
import com.learn.security.oauth2.auth.server.service.db.service.ISysPermService;
import com.learn.security.oauth2.auth.server.service.db.service.ISysRoleService;
import com.learn.security.oauth2.orm.SysRole;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 权限服务
 *
 * @author knight
 */
@Service
@AllArgsConstructor
public class PermissionsService {

	/**
	 * 权限服务
	 */
	private final ISysPermService permService;

	/**
	 * 角色服务
	 */
	private final ISysRoleService roleService;

	/**
	 * 根据用户id获取其角色列表
	 * @param userId userId
	 * @return Set<Role>
	 */
	public List<SysRole> selectRoleList(String userId) {
		return roleService.selectRoleList(userId);
	}

	/**
	 * 给用户添加角色
	 * @param userId 用户id
	 * @param roleIds 角色id
	 * @return boolean
	 */
	public boolean addRole(String userId, String... roleIds) {
		return roleService.addRole(userId, roleIds);
	}

	/**
	 * 通过角色id查询权限列表
	 * @param roleIds 角色id
	 * @return {@link Set<String>}
	 */
	public Set<String> selectPermSetByRoleIds(Set<String> roleIds) {
		return permService.selectPermSetByRoleIds(roleIds);
	}

	/**
	 * 通过角色列表查询权限列表
	 * @param sysRoles 系统角色
	 * @return {@link Set<String>}
	 */
	public Set<String> selectPermSetByRoles(List<SysRole> sysRoles) {
		if (CollUtil.isEmpty(sysRoles)) {
			return Collections.emptySet();
		}
		return selectPermSetByRoleIds(sysRoles.stream().map(SysRole::getId).collect(Collectors.toSet()));
	}

}
